from flask import Blueprint, render_template, jsonify, redirect, url_for, request, session, g
from exts import mail, db
from flask_mail import Message
import string
import random
from models import EmailCaptchaModel, UserModel, SpeciesModel, SiteModel, ProjectsModel
from .forms import RegisterForm, LoginForm, AddSpecies, AddSite, AddProjectForm
from werkzeug.security import generate_password_hash, check_password_hash
from decorators import login_required
from datetime import date
import json

bp = Blueprint("func", __name__, url_prefix="/func")

@bp.route("/index")
def index():
    return render_template("index_new.html")

@bp.route("/projects", methods=['GET','POST'])
@login_required
def myprojects():
    projects = ProjectsModel.query.filter_by(user_id=g.user.id).all()
    return render_template("projects_new.html",projects=projects)

@bp.route("/projects/add", methods=['GET','POST'])
@login_required
def AddProject():
    if request.method == 'POST':
        form = AddProjectForm(request.form)
        if form.validate():
            projectname = form.projectname.data
            projecttype = request.form.get('projecttype')
            userid = g.user.id
            data_input_default = {}
            if projecttype == 'SingleSite':
                data_input_default = {
                    "Site":"SE Qld",
                    "Species":"Trial",
                    "Latitude":-26,
                    "Fertility_rating":1,
                    "Soil_class":"CL",
                    "Maximum_ASW":300,
                    "Minimum_ASW":0,
                    "Atmospheric_CO2":350,
                    "Initial_biomass_pools":"a",
                    "Initial_WF":7,
                    "Initial_WR":2,
                    "Initial_WS":5,
                    "Stand_mass":0,
                    "WF_fraction":0,
                    "WR_fraction":0,
                    "WS_fraction":0,
                    "Seedling_mass":0,
                    "Initial_date":"a",
                    "Initial_year":1,
                    "Initial_month":1,
                    "Initial_age_y":0,
                    "Initial_age_m":0,
                    "Year_planted":1988,
                    "Month_planted":"June",
                    "Initial_stocking":1111,
                    "Initial_ASW":300,
                    "End_age":5,
                    "Interpolate_lookups":"N",
                    "Fertility":[
                        {"Age":3,"FR":1},
                        {"Age":5,"FR":0.5},
                        {"Age":7,"FR":0.3},
                        {"Age":99,"FR":0.1}
                    ],
                    "Irrigation":[
                        {"Age":6,"Ml_ha_yr":-4},
                        {"Age":10,"Ml_ha_yr":-1}
                    ],
                    "Thinning":[

                    ],
                    "Defoliation":[

                    ]
                }
            project = ProjectsModel(
                projectname=projectname,
                projecttype=projecttype,
                user_id=userid,
                data_input=json.dumps(data_input_default),
                data_output=""
            )
            db.session.add(project)
            db.session.commit()
            return redirect(url_for('func.myprojects'))
        else:
            print(form.errors)
            return redirect(url_for('func.myprojects'))

@bp.route("/projects/delete", methods=['GET','POST'])
@login_required
def DeleteProject():
    if request.method == 'POST':
        id = request.form.get('deleteProjectId')
        proj = ProjectsModel.query.get(id)
        db.session.delete(proj)
        db.session.commit()
        return redirect(url_for('func.myprojects'))

@bp.route("/sites", methods=['GET','POST'])
@login_required
def mysites():
    sites=[]
    if request.method == 'GET':
        sites = SiteModel.query.filter_by(user_id=g.user.id).all()
        return render_template("sites_new.html",sites=sites)
    else:
        return render_template("sites_new.html", sites=sites)

@bp.route("/sites/add", methods=['GET','POST'])
@login_required
def addsite():
    if request.method == 'GET':
        return redirect(url_for('func.mysites'))
    else:
        form = AddSite(request.form)
        if form.validate():
            name = form.sitename.data
            newsite = SiteModel(sitename=name, user_id=g.user.id)
            db.session.add(newsite)
            db.session.commit()
            return redirect(url_for('func.mysites'))
        else:
            print(form.errors)
            return redirect(url_for('func.mysites'))

@bp.route("/site/delete", methods=['GET','POST'])
@login_required
def deletesite():
    if request.method == 'GET':
        return redirect(url_for('func.mysites'))
    else:
        deleteId = request.form.get('deleteSiteId')
        site = SiteModel.query.get(deleteId)
        if site:
            db.session.delete(site)
            db.session.commit()
        return redirect(url_for('func.mysites'))

@bp.route("/site/edit/<int:siteId>", methods=['GET','POST'])
@login_required
def editsite(siteId):
    site = SiteModel.query.get(siteId)
    return render_template("siteedit_new.html", site=site)

@bp.route("/site/editsubmit/<int:siteId>", methods=['GET','POST'])
@login_required
def editsubmitsite(siteId):
    if request.method == 'GET':
        return redirect(url_for('func.editsite',siteId=siteId))
    else:
        site = SiteModel.query.get(siteId)

        site.create_time = date.today()

        site.tmax1 = request.form.get('tmax1')
        site.tmax2 = request.form.get('tmax2')
        site.tmax3 = request.form.get('tmax3')
        site.tmax4 = request.form.get('tmax4')
        site.tmax5 = request.form.get('tmax5')
        site.tmax6 = request.form.get('tmax6')
        site.tmax7 = request.form.get('tmax7')
        site.tmax8 = request.form.get('tmax8')
        site.tmax9 = request.form.get('tmax9')
        site.tmax10 = request.form.get('tmax10')
        site.tmax11 = request.form.get('tmax11')
        site.tmax12 = request.form.get('tmax12')

        site.tmin1 = request.form.get('tmin1')
        site.tmin2 = request.form.get('tmin2')
        site.tmin3 = request.form.get('tmin3')
        site.tmin4 = request.form.get('tmin4')
        site.tmin5 = request.form.get('tmin5')
        site.tmin6 = request.form.get('tmin6')
        site.tmin7 = request.form.get('tmin7')
        site.tmin8 = request.form.get('tmin8')
        site.tmin9 = request.form.get('tmin9')
        site.tmin10 = request.form.get('tmin10')
        site.tmin11 = request.form.get('tmin11')
        site.tmin12 = request.form.get('tmin12')

        site.precip1 = request.form.get('precip1')
        site.precip2 = request.form.get('precip2')
        site.precip3 = request.form.get('precip3')
        site.precip4 = request.form.get('precip4')
        site.precip5 = request.form.get('precip5')
        site.precip6 = request.form.get('precip6')
        site.precip7 = request.form.get('precip7')
        site.precip8 = request.form.get('precip8')
        site.precip9 = request.form.get('precip9')
        site.precip10 = request.form.get('precip10')
        site.precip11 = request.form.get('precip11')
        site.precip12 = request.form.get('precip12')

        site.evap1 = request.form.get('evap1')
        site.evap2 = request.form.get('evap2')
        site.evap3 = request.form.get('evap3')
        site.evap4 = request.form.get('evap4')
        site.evap5 = request.form.get('evap5')
        site.evap6 = request.form.get('evap6')
        site.evap7 = request.form.get('evap7')
        site.evap8 = request.form.get('evap8')
        site.evap9 = request.form.get('evap9')
        site.evap10 = request.form.get('evap10')
        site.evap11 = request.form.get('evap11')
        site.evap12 = request.form.get('evap12')

        site.ra1 = request.form.get('ra1')
        site.ra2 = request.form.get('ra2')
        site.ra3 = request.form.get('ra3')
        site.ra4 = request.form.get('ra4')
        site.ra5 = request.form.get('ra5')
        site.ra6 = request.form.get('ra6')
        site.ra7 = request.form.get('ra7')
        site.ra8 = request.form.get('ra8')
        site.ra9 = request.form.get('ra9')
        site.ra10 = request.form.get('ra10')
        site.ra11 = request.form.get('ra11')
        site.ra12 = request.form.get('ra12')

        site.raind1 = request.form.get('raind1')
        site.raind2 = request.form.get('raind2')
        site.raind3 = request.form.get('raind3')
        site.raind4 = request.form.get('raind4')
        site.raind5 = request.form.get('raind5')
        site.raind6 = request.form.get('raind6')
        site.raind7 = request.form.get('raind7')
        site.raind8 = request.form.get('raind8')
        site.raind9 = request.form.get('raind9')
        site.raind10 = request.form.get('raind10')
        site.raind11 = request.form.get('raind11')
        site.raind12 = request.form.get('raind12')

        site.frost1 = request.form.get('frost1')
        site.frost2 = request.form.get('frost2')
        site.frost3 = request.form.get('frost3')
        site.frost4 = request.form.get('frost4')
        site.frost5 = request.form.get('frost5')
        site.frost6 = request.form.get('frost6')
        site.frost7 = request.form.get('frost7')
        site.frost8 = request.form.get('frost8')
        site.frost9 = request.form.get('frost9')
        site.frost10 = request.form.get('frost10')
        site.frost11 = request.form.get('frost11')
        site.frost12 = request.form.get('frost12')

        db.session.commit()
        return redirect(url_for('func.editsite',siteId=siteId))

@bp.route("/species", methods=['GET','POST'])
@login_required
def myspecies():
    species = []
    if request.method == 'GET':
        species = SpeciesModel.query.filter_by(user_id=g.user.id).all()
        return render_template("species_new.html",species=species)
    else:
        return render_template("species_new.html",species=species)

@bp.route("/species/add", methods=['GET','POST'])
@login_required
def addspecies():
    if request.method == 'GET':
        return redirect(url_for('func.myspecies'))
    else:
        form = AddSpecies(request.form)
        if form.validate():
            name = form.speciesname.data
            newspecie = SpeciesModel(speciesname=name, user_id=g.user.id)
            db.session.add(newspecie)
            db.session.commit()
            return redirect(url_for('func.myspecies'))
        else:
            print(form.errors)
            return redirect(url_for('func.myspecies'))

@bp.route("/species/delete", methods=['GET','POST'])
@login_required
def deletespecies():
    if request.method == 'GET':
        return redirect(url_for('func.myspecies'))
    else:
        deleteid = request.form.get('deletespeciesid')
        specie = SpeciesModel.query.get(deleteid)
        if specie:
            db.session.delete(specie)
            db.session.commit()
        return redirect(url_for('func.myspecies'))

@bp.route("/species/edit/<int:speciesId>", methods=['GET','POST'])
@login_required
def editspecies(speciesId):
    species = SpeciesModel.query.get(speciesId)
    return render_template("speciesedit_new.html", species=species)

@bp.route("/species/editsubmit/<int:speciesId>", methods=['GET','POST'])
@login_required
def editsubmitspecies(speciesId):
    if request.method == 'GET':
        return redirect(url_for('func.editspecies',speciesId=speciesId))
    else:
        species = SpeciesModel.query.get(speciesId)

        species.create_time = date.today()

        species.pFS2 = request.form.get('pFS2')
        species.pFS20 = request.form.get('pFS20')
        species.aS = request.form.get('aS')
        species.nS = request.form.get('nS')
        species.pRx = request.form.get('pRx')
        species.pRn = request.form.get('pRn')

        species.gammaFx = request.form.get('gammaFx')
        species.gammaF0 = request.form.get('gammaF0')
        species.tgammaF = request.form.get('tgammaF')
        species.gammaR = request.form.get('gammaR')

        species.Tmin = request.form.get('Tmin')
        species.Topt = request.form.get('Topt')
        species.Tmax = request.form.get('Tmax')

        species.kF = request.form.get('kF')

        species.SWconst = request.form.get('SWconst')
        species.SWpower = request.form.get('SWpower')

        species.fCalpha700 = request.form.get('fCalpha700')
        species.fCg700 = request.form.get('fCg700')

        species.m0 = request.form.get('m0')
        species.fN0 = request.form.get('fN0')
        species.fNn = request.form.get('fNn')

        species.MaxAge = request.form.get('MaxAge')
        species.nAge = request.form.get('nAge')
        species.rAge = request.form.get('rAge')

        species.gammaNx = request.form.get('gammaNx')
        species.gammaN0 = request.form.get('gammaN0')
        species.tgammaN = request.form.get('tgammaN')
        species.ngammaN = request.form.get('ngammaN')
        species.wSx1000 = request.form.get('wSx1000')
        species.thinPower = request.form.get('thinPower')
        species.mF = request.form.get('mF')
        species.mR = request.form.get('mR')
        species.mS = request.form.get('mS')

        species.SLA0 = request.form.get('SLA0')
        species.SLA1 = request.form.get('SLA1')
        species.tSLA = request.form.get('tSLA')

        species.k = request.form.get('k')
        species.fullCanAge = request.form.get('fullCanAge')
        species.MaxIntcptn = request.form.get('MaxIntcptn')
        species.LAImaxIntcptn = request.form.get('LAImaxIntcptn')

        species.alpha = request.form.get('alpha')
        species.Y = request.form.get('Y')

        species.MinCond = request.form.get('MinCond')
        species.MaxCond = request.form.get('MaxCond')
        species.LAIgcx = request.form.get('LAIgcx')
        species.CoeffCond = request.form.get('CoeffCond')
        species.BLcond = request.form.get('BLcond')

        species.fracBB0 = request.form.get('fracBB0')
        species.fracBB1 = request.form.get('fracBB1')
        species.tBB = request.form.get('tBB')

        species.rhoMin = request.form.get('rhoMin')
        species.rhoMax = request.form.get('rhoMax')
        species.tRho = request.form.get('tRho')

        species.aH = request.form.get('aH')
        species.nHB = request.form.get('nHB')
        species.nHN = request.form.get('nHN')

        species.aV = request.form.get('aV')
        species.nVB = request.form.get('nVB')
        species.nVN = request.form.get('nVN')

        species.Qa = request.form.get('Qa')
        species.Qb = request.form.get('Qb')
        species.gDM_mol = request.form.get('gDM_mol')
        species.molPAR_MJ = request.form.get('molPAR_MJ')

        db.session.commit()
        return redirect(url_for('func.editspecies',speciesId=speciesId))

@bp.route("/enterproject/<int:projectId>", methods=['GET','POST'])
@login_required
def EnterProject(projectId):
    if request.method == 'GET':
        proj = ProjectsModel.query.get(projectId)
        projType = proj.projecttype
        if projType == 'SingleSite':
            return redirect(url_for('calc.EnterSingleSite', projectId=projectId))
        elif projType == 'MultiSite':
            return redirect(url_for('calc.EnterMultiSite', projectId=projectId))
        else:
            return redirect(url_for('calc.EnterSensitivity', projectId=projectId))
    else:
        pass

@bp.route("/help", methods=['GET','POST'])
@login_required
def gethelp():
    return render_template("help.html")

